package com.dz.wx.controller;

import io.swagger.annotations.ApiOperation;

import java.util.Map;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import springfox.documentation.annotations.ApiIgnore;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dz.customer.entity.Customer;
import com.dz.wx.entity.SessionInfo;
import com.dz.wx.entity.UserInfo;
import com.dz.wx.security.AES;
import com.dz.wx.service.WxCustomerService;
import com.dz.wx.service.WxService;
import com.dz.wx.vo.UserReq;

/**
 * 微信用户认证相关
 *
 */
@RestController
@Slf4j
public class WxAuthController extends BaseController {

	@Autowired
	private WxService wxService;
	@Autowired
	private WxCustomerService wxCustomerService;

	@ApiOperation(value = "获取用户信息接口", httpMethod = "POST")
	@RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
	public SessionInfo getUserInfo(@RequestBody UserReq userReq) {
		String wxCode = userReq.getCode();
		String encryptedData = userReq.getEncryptedData();
		String iv = userReq.getIv();
		Assert.notNull(wxCode, "code不能为空..");
		Map<String, Object> wxSessionMap = wxService.getWxSession(wxCode);
		if (null == wxSessionMap) {
			return null;
		}
		if (wxSessionMap.containsKey("errcode")) {
			log.warn("获取session失败..{}", wxSessionMap.get("errorCode"));
			return null;
		}
		String wxOpenId = (String) wxSessionMap.get("openid");
		String wxSessionKey = (String) wxSessionMap.get("session_key");
		Long expires = Long.valueOf(String.valueOf(wxSessionMap.get("expires_in")));
		log.info("get openId:{},sessionKey:{}", wxOpenId, wxSessionKey);
		try {
			AES aes = new AES();
			byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(wxSessionKey),
					Base64.decodeBase64(iv));
			if (null != resultByte && resultByte.length > 0) {
				String userInfo = new String(resultByte, "UTF-8");
				UserInfo info = JSON.parseObject(userInfo, UserInfo.class);
				Customer customer = new Customer();
				BeanUtils.copyProperties(userInfo, customer);
				Customer rawData = wxCustomerService.saveWxInfo(customer);
				info.setId(rawData.getId());
				String key = wxService.create3rdSessionInfo(info, expires);
				return new SessionInfo(key, info);
			} else {
				throw new IllegalArgumentException("获取用户信息失败");
			}
		} catch (Exception e) {
			throw new IllegalArgumentException(e.getMessage());
		}
	}

	@RequestMapping("/getSessionInfo")
	@ApiIgnore
	public JSONObject getSessionInfo(@RequestParam("key") String key) {
		return wxService.getByKey(key);
	}
}
